package controllers

import (
	"gin-AssetManagement/inits"
	"gin-AssetManagement/models"
	"gin-AssetManagement/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
	"strconv"
	"strings"
)

func UsersView(g *gin.Context) {
	g.HTML(http.StatusOK, "user/index.html", nil)
}
func GetRoles(g *gin.Context) {
	role, err := models.GetRoles()
	if err != nil {
		g.JSON(http.StatusOK, err.Error())
		return
	}
	var data []LayuiTransfer
	for _, v := range role {
		data = append(data, LayuiTransfer{
			Value: strconv.Itoa(int(v.ID)),
			Title: v.Name,
		})
	}
	g.JSON(http.StatusOK, data)
}
func UsersList(g *gin.Context) {
	pageStr := g.Query("page")
	page, _ := strconv.Atoi(pageStr)
	limitStr := g.Query("limit")
	limit, _ := strconv.Atoi(limitStr)
	name := g.Query("username")
	phone := g.Query("phone")
	status := g.Query("status")
	users, conut, err := models.GetUserLists(name, phone, status, page, limit)
	if err != nil {
		g.JSON(http.StatusOK, LayuiData{
			Code:  1,
			Msg:   "获取数据失败" + err.Error(),
			Count: conut,
			Data:  nil,
		})
		return
	}
	g.JSON(http.StatusOK, LayuiData{
		Code:  0,
		Msg:   "获取数据成功",
		Count: conut,
		Data:  users,
	})
}

// GetUserBasic 获取所有用户信息
// @Summary 获取所有用户信息
// @Schemes http
// @Tags 获取用户
// @Description 获取所有用户信息
// @Accept json
// @Produce json
// @Success 200 {json} {"code":0,"msg":"成功","data":users}
// @Router /users/getUsers [get]
func GetUserBasic(g *gin.Context) {
	user := models.Users{}
	err := user.GetUserBasicById()
	if err != nil {
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "获取失败",
			Data: err.Error(),
		})
		return
	}
	g.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "成功",
		"data": user,
	})
}
func CreateUserView(g *gin.Context) {
	g.HTML(http.StatusOK, "user/create.html", nil)
}

// CreateUser 添加用户
// @Summary 添加用户
// @Schemes http
// @Tags 添加用户
// @Description 添加用户
// @Accept json
// @Produce json
// @Param name query string true "用户名"
// @param password query string true "密码"
// @param repassword query string true "确认密码"
// @param phone query string true "电话"
// @param email query string true "邮箱"
// @param status query string true "状态"
// @Success 200 {json} {"code":0,"msg":"成功"}
// @Router /users/create [post]
func CreateUser(g *gin.Context) {
	user := models.Users{}
	currentLoggedUser := models.Users{}
	useridany, _ := g.Get("userID")
	userid, _ := utils.ConvertToUint(useridany)
	currentLoggedUser.ID = userid
	err := currentLoggedUser.GetUserBasicById()
	if err != nil {
		logrus.Error(err)
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "获取当前用户信息失败",
			Data: nil,
		})
		return
	}
	var userFormData UserFormData
	if err := g.ShouldBind(&userFormData); err != nil {
		if strings.Contains(err.Error(), "eqfield") {
			g.JSON(http.StatusOK, Respond{
				Code: 1,
				Msg:  "两次输入的密码不一致",
				Data: err.Error(),
			})
			return
		}
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "解析数据失败",
			Data: err.Error(),
		})
		return
	}
	// 生成随机数salt
	salt := utils.SaltGenerate()
	// 加密
	pwd := utils.Encryption(userFormData.Password, salt)
	user.PassWord = pwd
	user.Salt = salt
	user.Name = userFormData.Name
	user.Sex = uint8(userFormData.Sex)
	user.Status = userFormData.Status
	user.Phone = userFormData.Phone
	user.Email = userFormData.Email
	user.CreatedUser = &currentLoggedUser
	user.UpdatedUser = &currentLoggedUser
	getRoles, err := models.GetRolesByIds(utils.ExtractRolesValues(userFormData.Roles))
	if err != nil {
		logrus.Error(err)
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "查询角色失败:" + err.Error(),
			Data: nil,
		})
		return
	}
	user.Roles = getRoles
	// 验证结构体字段（字段校验）
	errs := inits.NewValidator().Struct(user)
	if errs != nil {
		logrus.Error(errs)
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "字段校验失败",
			Data: errs.Error(),
		})
		return
	}
	err = user.CreateUser()
	if err != nil {
		logrus.Error(err)
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "添加用户失败",
			Data: err.Error(),
		})
		return
	}
	g.JSON(http.StatusOK, Respond{
		Code: 0,
		Msg:  "添加用户成功",
		Data: nil,
	})
}

func EditUsersView(g *gin.Context) {
	//id, _ := strconv.Atoi(g.Param("id"))
	g.HTML(http.StatusOK, "user/edit.html", nil)
}

func EditUsers(g *gin.Context) {
	id, _ := strconv.Atoi(g.Param("id"))
	user := models.Users{}
	currentLoggedUser := models.Users{}
	useridany, _ := g.Get("userID")
	userid, _ := utils.ConvertToUint(useridany)
	currentLoggedUser.ID = userid
	err := currentLoggedUser.GetUserBasicById()
	var userFormData UserFormData
	if err := g.ShouldBind(&userFormData); err != nil {
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "解析数据失败",
			Data: err.Error(),
		})
		return
	}
	user.Name = userFormData.Name
	user.Sex = uint8(userFormData.Sex)
	user.Status = userFormData.Status
	user.Phone = userFormData.Phone
	user.Email = userFormData.Email
	user.UpdatedUser = &currentLoggedUser
	getRoles, err := models.GetRolesByIds(utils.ExtractRolesValues(userFormData.Roles))
	if err != nil {
		logrus.Error(err)
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "查询角色失败:" + err.Error(),
			Data: nil,
		})
		return
	}
	user.Roles = getRoles
	err = models.UpdateUserById(id, user)
	if err != nil {
		logrus.Error(err)
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "修改失败:" + err.Error(),
			Data: nil,
		})
		return
	}
	g.JSON(http.StatusOK, Respond{
		Code: 0,
		Msg:  "修改成功",
		Data: nil,
	})
}

func DelUsers(g *gin.Context) {
	strid := g.Param("id")
	id, _ := strconv.Atoi(strid)

	err := models.DelUserById(id)
	if err != nil {
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "删除失败:" + err.Error(),
			Data: nil,
		})
		return
	}
	g.JSON(http.StatusOK, Respond{
		Code: 0,
		Msg:  "删除成功",
		Data: nil,
	})
}
func UsersResetPassword(g *gin.Context) {
	strid := g.Param("id")
	id, _ := strconv.Atoi(strid)

	err := models.ResetPassword(id)
	if err != nil {
		g.JSON(http.StatusOK, Respond{
			Code: 1,
			Msg:  "重置失败" + err.Error(),
			Data: nil,
		})
		return
	}
	g.JSON(http.StatusOK, Respond{
		Code: 0,
		Msg:  "重置成功",
		Data: nil,
	})
}
